首页 > 试题广场 >

集合的所有子集(二)

[编程题]集合的所有子集(二)
  • 热度指数:3108 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个整数数组 nums ,其中可能包含重复元素,请你返回这个数组的所有可能子集。

返回的答案中不能包含重复的子集,将答案按字典序进行排序。

数据范围:数组长度满足 ,数组中元素大小满足
示例1

输入

[1,2]

输出

[[],[1],[1,2],[2]]
示例2

输入

[1]

输出

[[],[1]]
class Solution:
    def subsets(self , nums: List[int]) -> List[List[int]]:
        # write code here
        if len(nums)<=1:
            return [nums]
        res=[]
        nums.sort()
        def backtrace(start,path):
            res.append(path)
            add=set()
            for i in range(start,len(nums)):
                if nums[i] not in add:
                    add.add(nums[i])
                    cur_path=path+[nums[i]]
                    backtrace(1+i, cur_path)
        backtrace(0,[])
        #res.sort()
        return res

编辑于 2022-04-12 07:06:53 回复(0)

问题信息

难度:
1条回答 2375浏览

热门推荐

通过挑战的用户

查看代码